package org.apak.frontend;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apak.db.RepairServiceDAO;
import org.apak.log.FileLogger;
import org.apak.model.LoggedSubject;
import org.apak.model.ServiceRequest;
import org.apak.xslt.XMLBuilder;

/**
 * Servlet implementation class ServiceRequestMenuServlet
 */
public class ServiceRequestMenuServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private HttpSession session;
	private RepairServiceDAO dao = new RepairServiceDAO();
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
		LoggedSubject loggedSubject = (LoggedSubject) session.getAttribute("loggedSubject");
		//System.out.println(loggedSubject.isCustomer());
		if(loggedSubject == null || loggedSubject.isCustomer()) {
			RequestDispatcher dispatcher = request.getRequestDispatcher("error.jsp");
			dispatcher.forward(request, response);
		} else {
			if(session.getAttribute("currentServiceRequest") != null)
				session.removeAttribute("currentServiceRequest");
			ServiceRequest[] serviceRequestArray = dao.getServiceRequestList();
//			request.setAttribute("serviceRequestArray", serviceRequestArray);
			// get full file path
			String xsltFileName = getServletContext().getRealPath(
		                "/WEB-INF/xslt/serviceRequestMenu.xsl");
			// Servlet's response PrintWriter
			PrintWriter out = response.getWriter(); 
			XMLBuilder.makeXML(serviceRequestArray, xsltFileName, out);
			FileLogger.logMessage("Forwarded to /serviceRequestMenu by ServiceRequestMenuServlet.doGet().");
//			RequestDispatcher dispatcher = request.getRequestDispatcher("serviceRequestMenu.jsp");
//			dispatcher.forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String actionButton = request.getParameter("actionButton");
		if(actionButton != null)
			if(actionButton.equals("New request")) {
				FileLogger.logMessage("Forwarded to /serviceRequest by ServiceRequestMenuServlet.doPost().");
				response.sendRedirect("./serviceRequest");
			}
	}

}
